import socket
import json


class TCP_Receive:
    def __init__(self, ip, port, timeout=0.1):
        self.ip = ip
        self.port = port
        self.timeout = timeout
        self.bind()

    def bind(self):
        """
        连接函数，注意设置timeout时间可能会影响帧率
        :return: 无
        """
        self.tcp_server = socket.socket()
        print("Create connection......")
        try:
            self.tcp_server.connect((self.ip, self.port))
            self.tcp_server.settimeout(self.timeout)
        except:
            self.tcp_server.close()
            raise TimeoutError("Can not create connect!!!")
        print("Create Connection successful!")

    def __recv(self, bufsize):
        try:
            rec = self.tcp_server.recv(bufsize)
            rec = str(rec, encoding='utf8')
        except:
            return -1
        return rec

    def recv(self):
        header = self.__recv(2)
        if str(header, encoding='utf8') != "LE":
            return -1

        cls = self.__recv(1)
        if int.from_bytes(cls, 'little') != 4:
            return -1

        length = self.__recv(4)
        if length == -1:
            return -1

        header = self.__recv(2)
        if str(header, encoding='utf8') != "LE":
            return -1

        recv = self.__recv(int.from_bytes(length, 'little'))
        try:
            recv = self.__decode(recv)
        except:
            return -1
        return recv

    def __decode(self, msg):
        msg = str(msg, encoding='utf8')
        msg = json.loads(msg)
        return msg

    def close_socket(self):
        """
        Close socket \n
        :return: None
        """
        self.tcp_server.close()
